

local function get_common_inst()
    local inst = require("prefabs/npc_characters/__02__pigman_npc_common")():Common_Npc_Create()
    return inst
end
-------------------------------------------------------------------------------------------------------------
---- 园艺相关
local HORTICULTURE_ONEOF_TAGS = { "plant", "lichen", "oceanvine", "mushroom_farm", "kelp" }
local HORTICULTURE_CANT_TAGS = { "magicgrowth", "player", "FX", "leif", "pickable", "stump", "withered", "barren", "INLIMBO", "silviculture", "tree", "winter_tree" }
local function trygrowth(inst, maximize)
    if not inst:IsValid()
		or inst:IsInLimbo()
        or (inst.components.witherable ~= nil and inst.components.witherable:IsWithered()) then

        return false
    end

    if inst:HasTag("leif") then
        inst.components.sleeper:GoToSleep(1000)
        return true
    end

    if maximize then
        MaximizePlant(inst)
    end

    if inst.components.growable ~= nil then
        -- If we're a tree and not a stump, or we've explicitly allowed magic growth, do the growth.
        if inst.components.growable.magicgrowable or ((inst:HasTag("tree") or inst:HasTag("winter_tree")) and not inst:HasTag("stump")) then
            if inst.components.simplemagicgrower ~= nil then
                inst.components.simplemagicgrower:StartGrowing()
                return true
            elseif inst.components.growable.domagicgrowthfn ~= nil then
                -- The upgraded horticulture book has a delayed start to make sure the plants get tended to first
                inst.magic_growth_delay = maximize and 2 or nil
                inst.components.growable:DoMagicGrowth()

                return true
            else
                return inst.components.growable:DoGrowth()
            end
        end
    end

    if inst.components.pickable ~= nil then
        if inst.components.pickable:CanBePicked() and inst.components.pickable.caninteractwith then
            return false
        end
        if inst.components.pickable:FinishGrowing() then
			inst.components.pickable:ConsumeCycles(1) -- magic grow is hard on plants
			return true
		end
    end

    if inst.components.crop ~= nil and (inst.components.crop.rate or 0) > 0 then
        if inst.components.crop:DoGrow(1 / inst.components.crop.rate, true) then
			return true
		end
    end

    if inst.components.harvestable ~= nil and inst.components.harvestable:CanBeHarvested() and inst:HasTag("mushroom_farm") then
        if inst.components.harvestable:IsMagicGrowable() then
            inst.components.harvestable:DoMagicGrowth()
            return true
        else
            if inst.components.harvestable:Grow() then
                return true
            end
        end

    end

	return false
end

local function GrowNext(spell)
	while #spell._targets > 0 do
		local target = table.remove(spell._targets, 1)
		if target:IsValid() and trygrowth(target, spell._maximize) then
			if spell._count > 1 then
				spell._count = spell._count - 1
				spell:DoTaskInTime(0.1 + 0.3 * math.random(), GrowNext)
				return
			end
			break
		end
	end
	spell:Remove()
end

local function do_book_horticulture_spell(x, z, max_targets, maximize)
	local ents = TheSim:FindEntities(x, 0, z, 30, nil, HORTICULTURE_CANT_TAGS, HORTICULTURE_ONEOF_TAGS)
	local targets = {}
	for i, v in ipairs(ents) do
		if v.components.pickable ~= nil or v.components.crop ~= nil or v.components.growable ~= nil or v.components.harvestable ~= nil then
			table.insert(targets, v)
		end
	end

	if #targets == 0 then
		return false, "NOHORTICULTURE"
	end

	local spell = SpawnPrefab("book_horticulture_spell")
	spell.Transform:SetPosition(x, 0, z)
	spell._targets = targets
	spell._count = max_targets
	spell._maximize = maximize

	GrowNext(spell)

	return true
end

-- 使用入口
-- do_book_horticulture_spell(x, z, TUNING.BOOK_GARDENING_UPGRADED_MAX_TARGETS, true)
-- do_book_horticulture_spell(x, z, TUNING.BOOK_GARDENING_MAX_TARGETS)

-------------------------------------------------------------------------------------------------------------
------ 运作定时任务
local function Farming_Task_Start(inst)
    if inst.farming_setp == nil then
        inst.farming_setp = 0
    end

    inst:DoPeriodicTask(1,function()
        local Base_Point =  Vector3(inst:GetPlayer().Transform:GetWorldPosition())     --- 巡视基点坐标
        
        if inst.farming_setp == 0 then


        end
    
    
    
    
    
    end)

end
-------------------------------------------------------------------------------------------------------------
local function fn()
    local inst = get_common_inst()

    local builds = { "pig_build", "pigspotted_build" }
    inst.build = builds[math.random(#builds)]
    inst.AnimState:SetBuild(inst.build)
    ---------------------------------------------------------------------------------------------
    -- talker 组件   net_bool 帮助处理偏移
    -- local TALLER_TALKER_OFFSET = Vector3(0, -700, 0)
    -- local colours = {
    --     Vector3( 255 /255, 193 /255 , 37 /255),     -- Goldenrod1 橙黄色
    --     Vector3( 127 /255, 255 /255 , 0 /255),      --- Chartreuse 青绿色
    --     Vector3( 255 /255, 255 /255 , 0 /255),      --- yellow 黄色
    --     Vector3( 255 /255, 69 /255 , 0 /255),       -- OrangeRed 橘红色
    --     Vector3( 0 /255, 191 /255 , 255 /255),      -- DeepSkyBlue 天蓝色
    --     Vector3( 34 /255, 139 /255 , 34 /255),      -- ForestGreen 深绿色
    --     Vector3( 238 /255, 233 /255 , 233 /255),     -- Snow2  雪白色
    -- }
    -- inst:AddComponent("talker")

    inst.components.talker.fontsize = 35  --- defualt = 28
    inst.components.talker.font = TALKINGFONT
    inst.components.talker.colour = Vector3( 127 /255, 255 /255 , 0 /255)
    inst.components.talker.offset = Vector3(0, -410, 0)

    -- inst.components.talker.Say_old_batbat = inst.components.talker.Say
    -- inst.components.talker.Say = function(self,...)
    --     self:Say_old_batbat(...)
    --     self.color_num = math.random(#colours)
    --     -- self.color_num = self.color_num + 1
    --     -- if self.color_num > #colours then
    --     --     self.color_num = 1
    --     -- end
    --     self.colour = colours[self.color_num]
    -- end
    ---------------------------------------------------------------------------------------------

    if not TheWorld.ismastersim then
        return inst
    end
    ---------------------------------------------------------------------------------------
    if inst.components.named.name == nil then
        inst.components.named.possiblenames = inst.npc_base_lib:Get_Names()
        inst.components.named:PickNewName()
    end
    ---------------------------------------------------------------------------------------
    -- 保证无法被打死
    inst.components.health.DoDelta_old = inst.components.health.DoDelta
    inst.components.health.DoDelta = function(self,amount,...)
        self.currenthealth = self.maxhealth
        local ret = { (self:DoDelta_old(-0.1,...)) }
        self.currenthealth = self.maxhealth
        return unpack(ret)
    end
    ---------------------------------------------------------------------------------------

    -----------------------------------------------------------------------------------------------------------
    -- -- player link
    inst:ListenForEvent("player_link",function(inst,tar_player)
        inst.__link_player = tar_player
        inst.npc_base_lib:Set_Linked_Player(tar_player)
        if tar_player and tar_player:HasTag("player") then
            tar_player.__link_npc = inst
        end
        print("NPC",inst.prefab,"Link Player",tar_player)
    end)

    inst:ListenForEvent("player_unlink",function()
        if inst.__link_player then
            inst.__link_player.__link_npc = nil
        end
    end)

    inst:DoTaskInTime(0.1,function()
        if inst.Ready == true then
            return
        end

        if inst.__link_player == nil then
            inst:Remove()
            -- print("warning : npc.__link_player == nil , inst:Remove() ")
        else
            print("npc create and  link succeed")
        end
    end)

    function inst:GetPlayer()
        return self.__link_player
    end
    ---------------------------------------------------------------------------------------------------------------
    --------- 拾取动作有 fn 转阶段
    inst:ListenForEvent("action_pick",function(inst,fn)
        inst.AnimState:PlayAnimation("pig_pickup")
        inst.AnimState:PushAnimation("idle_loop")
        
        if fn and type(fn) == "function" then
            inst.__action_pick_fn = function(inst)
                fn(inst)
                if inst.__action_pick_fn then
                    inst:RemoveEventCallback("animover",inst.__action_pick_fn)
                end
            end
            inst:ListenForEvent("animover",inst.__action_pick_fn)
        end

    end)

    ---------------------------------------------------------------------------------------------------------------
    -- Farming_Task_Start(inst)
    ---------------------------------------------------------------------------------------------------------------
    return inst
end

return Prefab("monster_npc_pigman_farmer", fn)
